import React, { useContext, createContext, useState } from "react";


// 初始化上下文
const MyContext = createContext()

export default function ContxtDemo({ children }) {
  const [person, setPerson] = useState({ name: '夏天', age: 18, gender: '男' })
  const login = () => console.log('登录')
  const logout = () => console.log('退出')
  const changePerson = () => setPerson({ name: '周一帆', age: 17, gender: '女' })
  const { name, age, gender } = person
  return (
    <>
      <h2>useContext的使用</h2>
      <ul>
        <li>姓名: {name}</li>
        <li>年龄:{age}</li>
        <li>性别:{gender}</li>
      </ul>
      <button onClick={changePerson}>换人</button>
      <MyContext.Provider value={{ person, changePerson, login, logout }}>
        {children}
      </MyContext.Provider>
    </>
  )
}
export function A() {
  return (
    <>
      <h2>父组件</h2>
      <B />
    </>
  )
}

function B() {
  const { person, changePerson, login, logout } = useContext(MyContext)
  const { name, age, gender } = person
  return (
    <>
      <h3>孙子组件</h3>
      <hr></hr>
      <ul>
        <li>姓名: {name}</li>
        <li>年龄:{age}</li>
        <li>性别:{gender}</li>
      </ul>
      <button onClick={changePerson}>孙子组件换人</button>
      <button onClick={login}>登录</button>
      <button onClick={logout}>登出</button>


    </>
  )
}